package quick_search

import (
	"reflect"

	"gorm.io/gorm/schema"
)

// TODO:
// reflectObject 通过反射对象生成查询条件
func reflectObject(obj interface{}, cond *Condition) (*Condition, error) {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)
	switch t.Kind() {
	case reflect.Ptr:
		t = t.Elem()
		v = v.Elem()
	case reflect.Struct:
		break
	default:
		return cond, nil
	}

	var table string
	if tabler, ok := obj.(schema.Tabler); ok {
		table = tabler.TableName()
	}

	for i := 0; i < t.NumField(); i++ {
		vf := t.Field(i)
		vv := v.Field(i)
		tag, ok := vf.Tag.Lookup(_qsTagName)
		if !ok && vf.Anonymous {
			reflectObject(vv.Interface(), cond)
			continue
		} else if tag == "" {
			continue
		}

		condi, err := ParseCondition(tag, vf, v)
		if err != nil {
			return nil, err
		}

		if condi.Table == "" {
			condi.Table = table
		}

		cond.AddField(condi)
	}

	return cond, nil
}
